package com.base.core.dozer;


import com.github.dozermapper.core.DozerBeanMapperBuilder;
import com.github.dozermapper.core.Mapper;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

/**
 * 将对象中的属性值复制到新增对象的同名属性中
 */
public class DozerConvert {

    //持有Dozer单例, 避免重复创建DozerMapper消耗资源.
    public static final Mapper dozer = DozerBeanMapperBuilder.buildDefault();
    /**
     * 将src对象中的属性值复制到desc对象的同名属性中
     *
     * @param src  源
     * @param desc 目标
     */
    public static void copyProperties(Object src, Object desc) {
        dozer.map(src, desc);
    }

    /**
     * 将src对象中的属性值复制到新建的desc对象的同名属性中
     *
     * @param src
     * @param descClass
     * @return
     */
    public static <T> T copyProperties(Object src, Class<T> descClass) {
        return dozer.map(src, descClass);
    }

    /**
     * 将srcList中的元素复制到元素类型为descClass的List集合中
     *
     * @param srcList
     * @param descClass
     * @return
     */
    public static <T> List<T> copyList(List srcList, Class<T> descClass) {
        List<T> descList = new ArrayList<>();
        if (srcList != null) {
            for (Object obj : srcList) {
                T t = DozerConvert.copyProperties(obj, descClass);
                descList.add(t);
            }
        }
        return descList;
    }

    public static <T> List<T> copyList(Collection sourceList, Class<T> destinationClass) {
        List destinationList = new ArrayList();
        for (Iterator i$ = sourceList.iterator(); i$.hasNext(); ) {
            Object sourceObject = i$.next();
            Object destinationObject = dozer.map(sourceObject, destinationClass);
            destinationList.add(destinationObject);
        }
        return destinationList;
    }


}
